<?php
declare (strict_types = 1);

namespace app\adminapi\controller;

//use app\adminapi\services\Token;
use app\adminapi\business\AdminBusiness;
use app\adminapi\facade\Token;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\captcha\facade\Captcha;
use think\Exception;

class Login
{
    /**
     * 登录的接口
     * @return string
     */
    public function login(){

//        return encrypt_password(123456); 重置数据库用户的密码

        # 验证验证码
//        if (!captcha_check(request()->post('captcha'))) {
//            return  error(2004,"验证码错误");
//        }

        $username = request()->post('username');
        $password = request()->post('password');// 明文

        $adminInfo = \app\common\model\Admin::where('username',$username)->find();

        if (!$adminInfo) {
            return  error(2002,"用户名不存在");
        }

        if ($adminInfo->password != encrypt_password($password)) {
            return  error(2003,'密码不正确');
        }

        # 登录成功之后、查询对应的权限信息
        $auth = AdminBusiness::handleAuth($adminInfo->id,$adminInfo->role_id);


        # 调用服务类中的方法
//        $tokenObj = new Token();
//        $jwt = $tokenObj->createToken($adminInfo->id);

        # 通过门面实现对类中的方法实现静态调用
        $jwt = Token::createToken($adminInfo->id);

        return success(['token' => $jwt,'auth' => $auth],'success');
    }

    /**
     * 验证码接口
     */
    public function getCaptcha(){
        $uniqid = uniqid((string)rand(10000,99999));
//        $src = 'www.adminapi.pyg.com'.captcha_src();// 本地
        $src = 'http://tp.shadowsu.top/'.captcha_src($uniqid);//线上的地址
        return json([
            'src' => $src,
            'uniqid' => $uniqid

        ]);

    }

    /**
     * 退出登录的接口你
     */
    public function logout(){
        # 退出登录的时候、让token失效
        Token::deleteToken();
        return success();
    }


    /**
     * 注册接口
     */
    public function register(){
        try {
            $param  = request()->all();
            # 参数验证
            if ($param['is_green'] != 1 ){
                throw new Exception("请勾选协议",2001);
            }

            \app\common\model\Admin::create([
                'username' => $param['username'],
                'password' => encrypt_password($param['password']),
                'email' => $param['email'],
                'nickname' => $param['nick_name'],
            ]);
            return  success();
        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }
    }
}
